package com.eeepay.eeepay_v2.activity;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.adapter.AddProAdapter;
import com.eeepay.eeepay_v2.model.AgentProfitInfo;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.AllUtils;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.eeepay_v2.util.SPUtils;
import com.eeepay.v2_library.ui.ABBaseActivity;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.MerchantSearchProto;
import cn.eeepay.api.grpc.nano.MerchantSearchServiceGrpc;
import io.grpc.ManagedChannel;

/**
 * Created by Ching on 2017/2/27.
 * 新增代理商第二步 --- 选择业务产品
 */

public class AgentAddStep3 extends ABBaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private ListView listView;
    private Button nextBtn;
    private AddProAdapter adapter;
    private List<AgentProfitInfo> bpList, templist;
//    private AgentProfitInfo profitInfo;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_agent_add_step_3;
    }

    @Override
    protected void initWidget() {
        listView = getViewById(R.id.lv_add_agent);
        nextBtn = getViewById(R.id.btn_next);
        adapter = new AddProAdapter(this);
        sendHttpRequest(0);
    }

    @Override
    public void onClick(View v) {

        if (isSelected()) {
            templist = new ArrayList<>();
//            templist.addAll(bpList);
            Iterator iter = adapter.getIsSelected().entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String key_pbid = (String) entry.getKey();//获取到pbid的值
//                Boolean val = (Boolean)entry.getValue();
                for (int i = 0; i < bpList.size(); i++) {
                    AgentProfitInfo profitInfo = bpList.get(i);
                    if (key_pbid.equals(profitInfo.getBpId()))//pbid 相等的添加到临时的集合里；也就是用户勾选的集合
                    {
                        Log.i("AgentAddStep3", "onClick: " + profitInfo.toString());
                        templist.add(profitInfo);
                    }
                }
            }
//            //避免遍历删除触发ConcurrentModificationException
//            for (Iterator<AgentProfitInfo> it = templist.iterator(); it.hasNext(); ) {
//                if (!it.next().isApply())//未选中的去掉
//                    it.remove();
//            }

            SPUtils.saveList(templist, Constant.KEY.AGENT_ADD_LIST);
            AllUtils.addActivity(AgentAddStep3.this);
            goActivity(AgentAddStep4.class);
            templist.clear();
        } else {
            showToast("请勾选业务产品");
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        AgentProfitInfo profitInfo = (AgentProfitInfo) parent.getAdapter().getItem(position);
        profitInfo.setApply(!profitInfo.isApply());
//        adapter.notifyDataSetChanged();
        //勾选逻辑修改
   /*     1 首先判断是否可单独申请
          如果是否；把同一组的是勾选上
        2 取消的时候； 判断一下；如果是并且同一个组里有否的话； 去掉否勾选*/
        String apply = profitInfo.getAllowIndividualApply();//允许单独申请，1：是，0：否'
        String groupNo = profitInfo.getGroupNo();//产品组号
        if (!TextUtils.isEmpty(groupNo)) {//在有组的情况下

            if (adapter.getIsSelected().containsKey(profitInfo.getBpId())) //已经存在
                adapter.getIsSelected().remove(profitInfo.getBpId());//移除
            else
                adapter.getIsSelected().put(profitInfo.getBpId(), true);

            if (TextUtils.equals(apply, "0"))//不允许单独申请
            {
                for (int i = 0; i < bpList.size(); i++) {
                    AgentProfitInfo agentProfitInfo = bpList.get(i);
                    if (TextUtils.equals(agentProfitInfo.getGroupNo(), groupNo) && !agentProfitInfo.getBpId().equals(profitInfo.getBpId())) {//同一组的勾上
                        if (!adapter.getIsSelected().containsKey(agentProfitInfo.getBpId()))
                            adapter.getIsSelected().put(agentProfitInfo.getBpId(), true);
                    }
                }
            } else {
                //如果允许单独申请取消，否跟着取消
                for (int i = 0; i < bpList.size(); i++) {
                    AgentProfitInfo agentProfitInfo = bpList.get(i);
                    if (TextUtils.equals(agentProfitInfo.getGroupNo(), groupNo) && TextUtils.equals(agentProfitInfo.getAllowIndividualApply(), "0")) {//同一组的否移除掉
                        {
                            if (adapter.getIsSelected().containsKey(agentProfitInfo.getBpId())) {//已经存在
                                adapter.getIsSelected().remove(agentProfitInfo.getBpId());//移除
                                break;
                            }
                        }
                    }
                }
            }
        } else {//没有组的情况下；一一对应；
            if (!adapter.getIsSelected().containsKey(profitInfo.getBpId()))
                adapter.getIsSelected().put(profitInfo.getBpId(), true);
            else
                adapter.getIsSelected().remove(profitInfo.getBpId());
        }
        adapter.notifyDataSetChanged();

    }

    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT, taskId, new GrpcUtils.AsyncTaskListener() {
            //        GrpcUtils.getInstance().doGrpcTask("192.168.4.4", "8090", taskId, new GrpcUtils.AsyncTaskListener() {
            @Override
            public Object doInBack(ManagedChannel channel, int taskId) {
                MerchantSearchServiceGrpc.MerchantSearchServiceBlockingStub stub = MerchantSearchServiceGrpc
                        .newBlockingStub(channel).withDeadlineAfter(30, TimeUnit.SECONDS);
                MerchantSearchProto.BpdReq req = new MerchantSearchProto.BpdReq();
                req.agentNo = UserInfo.getUserInfo2SP().getAgentNo();
                return stub.getBpId(req);
            }

            @Override
            public void updateUI(Object result, int taskId) {
                dismissProgressDialog();
                if (result == null)
                    return;
                MerchantSearchProto.BpdRes response = (MerchantSearchProto.BpdRes) result;
//                bpList = Arrays.asList(response.pbdInfo);
//                for (MerchantSearchProto.PbdInfo pbdInfo : bpList){
//                    LogUtils.d(" pbdInfo = " + pbdInfo.bpId + " | "+pbdInfo.bpName);
//                }
                if (!response.success) {
                    showToast(response.msg);
                    return;
                }
                bpList = new ArrayList<>();
                MerchantSearchProto.PbdInfo pbdInfo;
                for (int i = 0; i < response.pbdInfo.length; i++) {
                    AgentProfitInfo profitInfo = new AgentProfitInfo();
                    pbdInfo = response.pbdInfo[i];
                    profitInfo.setBpName(pbdInfo.bpName);
                    profitInfo.setBpId(pbdInfo.bpId);
                    profitInfo.setRemark(pbdInfo.remark);
                    profitInfo.setBpType(pbdInfo.bpType);
                    //新增2个字段
                    profitInfo.setAllowIndividualApply(pbdInfo.allowIndividualApply);
                    profitInfo.setGroupNo(pbdInfo.groupNo);
                    bpList.add(profitInfo);
                }

                adapter.addAll(bpList);
                listView.setAdapter(adapter);
            }
        });
    }

    @Override
    protected void eventOnClick() {
        listView.setOnItemClickListener(this);
        nextBtn.setOnClickListener(this);
    }

    public boolean isSelected() {
        if (!adapter.getIsSelected().isEmpty() && adapter.getIsSelected().size() > 0) {
            return true;
        }
//        for (AgentProfitInfo profitInfo : bpList) {
//            if (profitInfo.isApply()) {
//                return true;
//            }
//        }
        return false;
    }

}
